package com.firefly.web.utils;
import com.firefly.dao.util.RedisUtils;
import com.firefly.util.handle.FireflyException;
import com.firefly.util.utils.FuncUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @description: 验证码生成、校验
 * @author: lzg(萤火科技 ： 854378082 @ qq.com)
 * @date: 2023/2/9
 **/
@Component
public class CodeUtils {
    private final RedisUtils redisUtils;
    @Autowired
    public CodeUtils(RedisUtils redisUtils){
        this.redisUtils = redisUtils;
    }
    public String getCode(String phone){
        String code = FuncUtils.getRandomNumber(6);
        redisUtils.set("code:" + phone,code,5*60);
        return code;
    }
    public void havCode(String phone){
        long time = redisUtils.getExpire("code:" + phone);
        if (time > 0){
            throw new FireflyException(403,"不要频繁获取验证码");
        }
    }
    public void verifyCode(String phone,String code){
        String redisCode = (String) redisUtils.get("code:" + phone);
        if (!redisCode.equals(code)){
            throw new FireflyException(403,"验证码无效");
        }
    }
    public void removeCode(String phone){
        redisUtils.del("code:" + phone);
    }
}
